package com.qqtech.web.context;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.qqtech.core.common.constant.CoreConst;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.exception.LoginException;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.exception.PayException;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.Result;

@ControllerAdvice
public class WebExceptionHandler implements HandlerExceptionResolver {
	private Logger log = LoggerFactory.getLogger(WebExceptionHandler.class);

	@ExceptionHandler(LoginException.class)
	@ResponseBody
	public Result handleUnexpectedServerError(LoginException e) {
		e.printStackTrace();
		log.debug(TimeUtil.now() + "-web系统出现异常：{}", e.getMessage());
		return new Result(RespEnum.EXCEPTION, "系统繁忙，请稍后再试");
	}

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		PrintWriter writer = null;
		String errStr = "系统繁忙，请稍后再试";
		int code = RespEnum.EXCEPTION.getCode();
		try {
			if (ex instanceof LoginException) {
				code = RespEnum.LOGIN.getCode();
				if (StringUtils.isNotBlank(ex.getMessage())) {
					errStr = RespEnum.LOGIN.getDesc();
				}
			} else if (ex instanceof BizzException || ex instanceof PayException || ex instanceof OrderException) {
				if (StringUtils.isNotBlank(ex.getMessage())) {
					errStr = ex.getMessage();
				}
			} else if (ex.getMessage().indexOf(LoginException.class.getName()) >= 0) {
				code = RespEnum.LOGIN.getCode();
				errStr = CoreConst.VALUE_CORE_UNLOGIN_MSG;
			}
			Result retDomain = new Result();
			retDomain.setCode(code);
			retDomain.setMsg(errStr);
			String json = JsonUtil.toJson(retDomain);
			writer = response.getWriter();
			writer.write(json);
			writer.flush();
			log.error("系统异常,e={},{}", ex, ex.getStackTrace());
			ex.printStackTrace();
		} catch (Exception e) {
			log.error("服务异常,e={},{}", e, e.getStackTrace());
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
		return null;
	}
}
